<template>
  <div class="subtitle-form-panel-container" v-if="selectedDrama">
    <div class="panel-header">
      <div class="header-content">
        <span class="header-title">字幕请求</span>
      </div>
    </div>
    
    <!-- 将标签页移到头部下方，便于快速切换 -->
    <div class="tabs-header">
      <el-tabs v-model="activeRequestTab" class="header-request-tabs" size="default">
        <el-tab-pane label="剧集请求" name="episodeRequest"></el-tab-pane>
        <el-tab-pane label="整个短剧请求" name="dramaRequest"></el-tab-pane>
      </el-tabs>
    </div>
    
    <div v-loading="loadingEpisodes" element-loading-text="加载剧集..." class="form-container">
      <!-- 剧集请求内容 -->
      <div v-if="activeRequestTab === 'episodeRequest'" class="episode-section">
        <el-divider v-if="hasSelection" content-position="left">字幕请求表单</el-divider>
        
        <div class="styled-form-section" v-if="hasSelection">
          <p class="section-title">
            <span v-if="selectedEpisode">为剧集ID: {{ selectedEpisode.episodeId }} 请求字幕</span>
            <span v-else-if="selectedEpisodes.length > 0">为选中的 {{ selectedEpisodes.length }} 个剧集批量请求字幕</span>
          </p>
          
          <el-form
            ref="subtitleFormRef"
            :model="episodeForm"
            label-width="120px"
            :class="{ 'form-disabled': selectionMode === 'none' }"
            class="subtitle-request-form"
          >
            <div class="form-group">
              <div class="form-group-title">字幕设置</div>
              
              <el-form-item label="当前短剧语言" prop="sourceLanguage">
                <el-select 
                  v-model="episodeForm.sourceLanguage" 
                  placeholder="选择当前短剧语言" 
                  style="width: 100%;" 
                  filterable 
                  :disabled="selectionMode === 'none'"
                >
                  <el-option
                    v-for="lang in availableLanguages"
                    :key="lang.countryId"
                    :label="lang.countryLanguage + ' (' + lang.countryName + ')'"
                    :value="lang.countryLanguage">
                  </el-option>
                </el-select>
              </el-form-item>
              
              <LanguageSelector
                v-model="episodeForm.languages"
                :available-languages="availableLanguages"
                :source-language="episodeForm.sourceLanguage"
                :include-source-language="episodeForm.includeSourceLanguage"
                :disabled="selectionMode === 'none'"
                :error="formErrors.languages"
                @update:includeSourceLanguage="episodeForm.includeSourceLanguage = $event"
              />
            </div>
            
            <el-divider></el-divider>
            
            <el-form-item class="form-actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="handleSubmitEpisodeRequest" 
                :disabled="!canSubmitEpisodeRequest"
                class="submit-btn"
                :icon="Promotion"
              >
                生成字幕
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <el-empty v-else description="请选择剧集" class="selection-empty" image-size="100">
          <template #description>
            <span style="color: #64748b; font-size: 15px; font-weight: 500;">请从中间列表选择一个或多个剧集</span>
          </template>
        </el-empty>
      </div>

      <!-- 整剧请求内容 -->
      <div v-else-if="activeRequestTab === 'dramaRequest'" class="entire-drama-section">
        <p class="section-title">为整个短剧 "{{ selectedDrama.title }}" 请求字幕</p>
        <el-divider></el-divider>
        
        <div class="drama-stats drama-stats-beauty">
          <p>总剧集数: <strong>{{ episodes.length }}</strong></p>
          <p>可请求剧集数: <strong>{{ enabledEpisodes.length }}</strong></p>
        </div>
        
        <div class="styled-form-section">
          <el-form
            ref="dramaFormRef"
            :model="dramaForm"
            label-width="120px"
            class="subtitle-request-form"
          >
            <div class="form-group">
              <div class="form-group-title">字幕设置</div>
              
              <el-form-item label="当前短剧语言" prop="sourceLanguage">
                <el-select 
                  v-model="dramaForm.sourceLanguage" 
                  placeholder="选择当前短剧语言" 
                  style="width: 100%;" 
                  filterable
                >
                  <el-option
                    v-for="lang in availableLanguages"
                    :key="lang.countryId"
                    :label="lang.countryLanguage + ' (' + lang.countryName + ')'"
                    :value="lang.countryLanguage">
                  </el-option>
                </el-select>
              </el-form-item>
              
              <LanguageSelector
                v-model="dramaForm.languages"
                :available-languages="availableLanguages"
                :source-language="dramaForm.sourceLanguage"
                :include-source-language="dramaForm.includeSourceLanguage"
                :error="formErrors.languages"
                @update:includeSourceLanguage="dramaForm.includeSourceLanguage = $event"
              />
            </div>
            
            <el-divider></el-divider>
            
            <el-form-item class="form-actions">
              <el-button 
                type="success" 
                size="large"
                @click="handleSubmitDramaRequest" 
                :disabled="!canSubmitDramaRequest"
                class="submit-btn"
                :icon="Finished"
              >
                为整个短剧生成字幕
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
  
  <div v-else class="empty-form-panel-container">
    <el-empty description="请选择影视剧" image-size="120">
      <template #description>
        <span style="color: #64748b; font-size: 16px; font-weight: 500;">请先从左侧选择一部影视剧进行字幕请求</span>
      </template>
    </el-empty>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Promotion, Finished } from '@element-plus/icons-vue'
import { useSubtitleRequestStore } from '../../stores/subtitleRequest'
import { useFormValidation } from '../../composables/useFormValidation'
import LanguageSelector from './LanguageSelector.vue'
import type { Drama, Episode, LanguageOption } from '../../api/drama'

interface Props {
  selectedDrama: Drama | null
  episodes: Episode[]
  loadingEpisodes: boolean
  availableLanguages: LanguageOption[]
}

interface Emits {
  (e: 'submit-request', data: any): void
  (e: 'submit-request-for-entire-drama', data: any): void
  (e: 'request-submitted'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const store = useSubtitleRequestStore()
const { formErrors, validateSubtitleForm, validateDramaForm, clearErrors } = useFormValidation()

const subtitleFormRef = ref<FormInstance>()
const dramaFormRef = ref<FormInstance>()

const activeRequestTab = computed({
  get: () => store.activeRequestTab,
  set: (value) => store.activeRequestTab = value
})

const selectedEpisode = computed(() => store.selectedEpisode)
const selectedEpisodes = computed(() => store.selectedEpisodes)
const episodeForm = computed(() => store.episodeForm)
const dramaForm = computed(() => store.dramaForm)

const selectionMode = computed(() => store.selectionMode)
const canSubmitEpisodeRequest = computed(() => store.canSubmitEpisodeRequest)
const canSubmitDramaRequest = computed(() => store.canSubmitDramaRequest)

const hasSelection = computed(() => selectedEpisode.value || selectedEpisodes.value.length > 0)
const enabledEpisodes = computed(() => props.episodes.filter(ep => ep.status === 0))

const handleSubmitEpisodeRequest = async () => {
  clearErrors()
  
  const episodesToSubmit = selectedEpisodes.value.length > 0 
    ? selectedEpisodes.value 
    : (selectedEpisode.value ? [selectedEpisode.value] : [])
  
  const validation = validateSubtitleForm(episodeForm.value, episodesToSubmit)
  
  if (!validation.valid) {
    ElMessage.warning('请检查表单填写是否正确')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定为选中的 ${episodesToSubmit.length} 个剧集请求字幕吗?`,
      '请求确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )

    let requestLanguages = [...episodeForm.value.languages]
    if (episodeForm.value.includeSourceLanguage && !requestLanguages.includes(episodeForm.value.sourceLanguage)) {
      requestLanguages.push(episodeForm.value.sourceLanguage)
    }

    emit('submit-request', {
      episodes: episodesToSubmit,
      languages: requestLanguages,
      sourceLanguage: episodeForm.value.sourceLanguage
    })
    
    emit('request-submitted')
  } catch {
    ElMessage.info('请求已取消')
  }
}

const handleSubmitDramaRequest = async () => {
  clearErrors()
  
  const validation = validateDramaForm(dramaForm.value, props.episodes)
  
  if (!validation.valid) {
    ElMessage.warning('请检查表单填写是否正确')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定为短剧 "${props.selectedDrama?.title}" 的所有 ${enabledEpisodes.value.length} 个已启用剧集请求字幕吗?`,
      '整剧请求确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )

    let requestLanguages = [...dramaForm.value.languages]
    if (dramaForm.value.includeSourceLanguage && !requestLanguages.includes(dramaForm.value.sourceLanguage)) {
      requestLanguages.push(dramaForm.value.sourceLanguage)
    }

    emit('submit-request-for-entire-drama', {
      episodes: enabledEpisodes.value,
      languages: requestLanguages,
      sourceLanguage: dramaForm.value.sourceLanguage
    })
    
    emit('request-submitted')
  } catch {
    ElMessage.info('整剧请求已取消')
  }
}
</script>

<style scoped>
/* 这个组件的样式现在主要由主组件统一管理 */
/* 这里只需要添加组件特定的样式 */

.subtitle-form-panel-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  overflow: hidden;
}

.panel-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

/* 头部标签页样式 - 优雅顶部设计 */
.tabs-header {
  padding: 0 20px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.header-request-tabs {
  margin: 0;
}

.header-request-tabs .el-tabs__header {
  margin: 0;
  background: none;
  border: none;
}

.header-request-tabs .el-tabs__nav-wrap {
  background: none;
  border: none;
}

.header-request-tabs .el-tabs__nav-wrap::after {
  display: none;
}

.header-request-tabs .el-tabs__item {
  padding: 16px 24px;
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
  background: none;
  border: none;
  border-radius: 8px 8px 0 0;
  margin-right: 6px;
  transition: all 0.2s ease;
}

.header-request-tabs .el-tabs__item:hover {
  color: #3b82f6;
  background: rgba(59, 130, 246, 0.08);
}

.header-request-tabs .el-tabs__item.is-active {
  color: #3b82f6;
  background: #ffffff;
  font-weight: 600;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 1;
}

.header-request-tabs .el-tabs__active-bar {
  background: #3b82f6;
  height: 3px;
}

.form-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.episode-section,
.entire-drama-section {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.empty-form-panel-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fafbfc;
  align-items: center;
  justify-content: center;
}

/* 表单区域 - 精致优雅 */
.styled-form-section {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 24px;
  margin-top: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
  padding: 10px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.section-title span {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

/* 表单组 - 优雅设计 */
.form-group {
  margin-bottom: 20px;
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.form-group-title {
  font-size: 14px;
  font-weight: 600;
  color: #3b82f6;
  margin-bottom: 16px;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
  display: inline-block;
}

/* 表单操作区域 */
.form-actions {
  margin-top: 24px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.submit-btn {
  width: 100%;
  font-size: 16px;
  font-weight: 600;
  padding: 14px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 统计信息 - 优雅展示 */
.drama-stats-beauty {
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  border: 1px solid #bfdbfe;
  border-radius: 10px;
  padding: 20px;
  margin: 16px 0;
}

.drama-stats-beauty p {
  margin: 8px 0;
  font-size: 14px;
  color: #1e293b;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.drama-stats-beauty strong {
  color: #3b82f6;
  font-weight: 600;
  font-size: 16px;
}

/* 空状态 - 温馨提示 */
.selection-empty {
  margin-top: 16px;
  padding: 24px;
  text-align: center;
  background: linear-gradient(135deg, #fefbf3 0%, #fef3c7 100%);
  border: 1px solid #fcd34d;
  border-radius: 10px;
}

/* 表单禁用状态 */
.form-disabled {
  opacity: 0.7;
  pointer-events: none;
}

/* 错误状态优化 */
:deep(.el-form-item.is-error .el-form-item__label) {
  color: #ef4444;
}

:deep(.el-form-item__error) {
  color: #ef4444;
  font-size: 12px;
  margin-top: 4px;
  font-weight: 500;
}
</style>